<?php
namespace app\live\controller\api;
use app\ApiController;
use app\channel\model\ChannelGoodsModel;
use app\live\model\ChargeRulesModel;
use app\live\model\GiftLogModel;
use app\live\model\GiftModel;
use app\live\model\LiveGoodsModel;
use app\live\model\LiveRoomModel;
use app\member\model\AccountModel;
use app\member\model\UsersModel;
use app\shop\model\GoodsModel;
use lib\Redis;
use tencent\IMGroup;
use think\Db;
use think\facade\Cache;
use TlsSigApi\TLSSigAPIv2;

/*------------------------------------------------------ */
//-- 直播相关
/*------------------------------------------------------ */
class Live extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->checkLogin();//验证登陆
    }

    public function getInfo(){
        $role = input('role', 'player', 'trim');

        $room = (new LiveRoomModel())->getLastOne();

        if (empty($room) && $role == 'player'){
            return $this->success([
                'code' => 404,
                'url' => '/',
                'content' => '当前直播未开启, 请稍后再来',
                'btnTxt' => '返回首页'
            ]);
        }

    	$user_id = $this->userInfo['user_id'];

    	$key = 'tencent_user_sign_' . $user_id;

    	$userSig = Cache::get($key);

        $SDKAppID = settings('tx_SDKAppID');
        $secretKey = settings('tx_secretKey');
        $playDomain = settings('tx_pull_url');
        $liveDomainName = settings('tx_push_url');

    	if (empty($userSig)){
            $tls = new TLSSigAPIv2($SDKAppID, $secretKey);
            $expire = 86400 * 180;
            $userSig = $tls->genUserSig($user_id, $expire);
            Cache::set($key, $userSig, $expire - 3600);
        }



        $chatInfo = [
            'groupId' => $room['roomid'],
            'userID' => (String) $user_id,
            'userSig' => $userSig,
            'SDKAppID' => $SDKAppID,
            'liveDomainName' => $liveDomainName,
            'playDomain' => $playDomain,
            'streamId' => $room['stream_id'],
            'role' => '',
            'resolution' => '',
            'room_bg' => $room['cover_img']
        ];

    	$data['chatInfo'] = $chatInfo;

        $userinfo = $this->userInfo;
        if (empty($userinfo['nick_name'])) $userinfo['nick_name'] = mobileSubstr($userinfo['mobile']);
    	$data['userInfo'] = $userinfo;
    	if ($role == 'live'){
            $data['anchorInfo'] = $userinfo;
        }else{
            $data['anchorInfo'] = (new UsersModel())->getInfo('user_id='.$room['anchor_user_id']);
        }
        if (empty($data['anchorInfo']['nick_name'])) $data['anchorInfo']['nick_name'] = mobileSubstr($data['anchorInfo']['mobile']);

    	return $this->success($data);
	}
    /*------------------------------------------------------ */
    //-- 回播获取房间相关信息
    /*------------------------------------------------------ */
    public function getRoomReplay(){
        $roomid = input('roomid',0,'intval');
        if ($roomid < 1){
            return $this->error('房间ID传参失败.');
        }
        $roomInfo = (new LiveRoomModel)->getLiveRoomByRoomid($roomid);
        if (empty($roomInfo)){
            return $this->error('没有找到相关房间信息.');
        }
        if ($roomInfo['is_replay'] == 0){
            return $this->error('此房间暂未开放回放.');
        }
        return $this->success($roomInfo->toArray());
    }

    public function createRoom(){
        $name = input('name','','trim');
        $thumb = input('thumb','','trim');
        if (empty($name)){
            return $this->error('请设置直播标题.');
        }
        $anchor_id = $this->userInfo['user_id'];
        $SDKAppID = settings('tx_SDKAppID');
        $imGroup = new IMGroup($SDKAppID, settings('tx_secretKey'));
        //$imGroup->destroyAllGroup();
        //$res = $imGroup->getGroupList();
        //dump($res);
        //exit;
        $group_id = time();
        $res = $imGroup->createGroup($name, $anchor_id, $group_id);
        if ($res['code'] !== 0){
            //return $this->error('创建直播群失败!!');
            return $this->error($res['ErrorInfo']);
        }

        /*if ($thumb){
            $extend = getFileExtend($thumb);
            if ($extend == false){
                return $this->error('未能识别图片，请尝试重新上传.');
            }
            $file_path = config('config._upload_') . 'live/' . date('Ym'). '/';
            $file_name = $group_id . '.' . $extend[1];
            $res = base64ToImage($thumb, $file_path, $file_name);
            if ($res == false){
                return $this->error('图片保存失败，请重试.');
            }
            $upArr['cover_img'] = trim($file_path . $file_name, '.');
        }*/

        $data['thumb'] = $thumb;
        $data['roomid'] = $group_id;
        $data['name'] = $name;
        $data['live_status'] = 101;
        $data['stream_id'] = $SDKAppID . '_' . $data['roomid'] . '_' . $anchor_id . '_main';

        $liveRoomModel = new LiveRoomModel();
        $res = $liveRoomModel->saveRoom($this->userInfo, $data);
        if ($res){
            return $this->success($data);
        }
        return $this->error('创建直播间失败.');
    }

    public function endLive(){
        $group_id = input('group_id','','trim');
        if (empty($group_id)) return $this->error('参数错误.');

        $liveRoomModel = new LiveRoomModel();
        $room = $liveRoomModel->getLiveRoomByRoomid($group_id);

        if (empty($room)) return $this->error('直播间不存在.');

        $redis = new Redis();
        $user_key = 'live_user_roomid_' . $group_id;
        $num = $redis->zCard($user_key);

        $res = $liveRoomModel->where('roomid', $group_id)->update(['end_time' => time(), 'live_status' => 103, 'nums' => $num]);

        if ($res){
            $redis->zRemRangeByRank($user_key, 0, -1);
            $like_key = 'live_like_roomid_' . $group_id;
            Cache::rm($like_key);

            return $this->success('成功');
        }
        return $this->error('停播失败');
    }

    public function getGiftList(){

        $list = (new GiftModel())->getAllGift();
        $data['giftList'] = $list;

        return $this->success($data);
    }

    public function sendGift(){
        $gift_id = input('gift_id', 0, 'intval');
        $gift_num = input('gift_num', 0, 'intval');
        $roomid = input('roomid', 0, 'intval');
        if ($gift_id <= 0 && $gift_num <= 0 && $roomid <= 0) return $this->error('参数错误');

        $giftList = (new GiftModel())->getAllGift();
        $gift_info=array();
        foreach($giftList as $k=>$v){
            if($gift_id == $v['id']){
                $gift_info=$v;
            }
        }
        if(!$gift_info) return $this->error('礼物不存在');

        $room = (new LiveRoomModel())->getLiveRoomByRoomid($roomid);
        if(!$room) return $this->error('直播间不存在');

        $user_id = $this->userInfo['user_id'];
        $total = $gift_info['gift_price'] * $gift_num;

        $accountModel = new AccountModel();
        $userAccount = $accountModel->where('user_id', $user_id)->find();

        if ($userAccount['balance_money'] < $total) return $this->error('账户余额不足,请充值');

        Db::startTrans();
        $changedata['change_desc'] = '直播赠送礼物扣除';
        $changedata['change_type'] = 21;
        $changedata['goods_id'] = $gift_id;
        $changedata['balance_money'] = $total * -1;
        $res = $accountModel->change($changedata, $user_id, false);
        if ($res !== true) {
            Db::rollback();// 回滚事务
            return $this->error('扣减余额失败.');
        }

        $giftLog['user_id'] = $user_id;
        $giftLog['roomid'] = $room['roomid'];
        $giftLog['anchor_id'] = $room['anchor_user_id'];
        $giftLog['gift_id'] = $gift_id;
        $giftLog['gift_price'] = $gift_info['gift_price'];
        $giftLog['num'] = $gift_num;
        $giftLog['total'] = $total;
        $giftLog['create_time'] = time();

        $re = (new GiftLogModel())->save($giftLog);

        if ($re){

            $redis = new Redis();
            $key = 'live_user_roomid_' . $roomid;
            $score = 1000000 + $total;
            $redis->zAdd($key, $score, $this->userInfo['user_id']);

            Db::commit();
            return $this->success('ok');
        }

        Db::rollback();
        return $this->error('操作失败,请重试!');
    }

    public function getUserAccountInfo(){
        $accountModel = new AccountModel();
        $userAccount = $accountModel->where('user_id', $this->userInfo['user_id'])->find();
        $data['account'] = $userAccount;
        return $this->success($data);
    }

    public function enterRoom(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');

        $user_id = $this->userInfo['user_id'];

        $redis = new Redis();
        $key = 'live_user_roomid_' . $roomid;
        $score = $redis->zScore($key, $user_id);
        if ($score > 1000000) return $this->success();

        $count = $redis->zCard($key);
        $score = 1000000 - $count;
        $res = $redis->zAdd($key, $score, $user_id);

        return $this->success($res);
    }

    public function exitRoom(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');

        $user_id = $this->userInfo['user_id'];

        $redis = new Redis();
        $key = 'live_user_roomid_' . $roomid;
        $res = $redis->zRem($key, $user_id);

        return $this->success($res);
    }

    public function getOnlineUser(){
        $p = input('p', 1, 'intval');
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');
        $size = 10;
        $start = ($p - 1) * $size;
        $stop = $start + $size - 1;

        $redis = new Redis();
        $key = 'live_user_roomid_' . $roomid;
        $num = $redis->zCard($key);
        $user_ids = $redis->zRevRange($key, $start, $stop,true);

        $userList = [];

        $userModel = new UsersModel();

        foreach($user_ids as $k=>$v){
            $userinfo = $userModel->info($k);
            unset(
                $userinfo['id_card_number'],
                $userinfo['id_card_positive'],
                $userinfo['id_card_back'],
                $userinfo['id_card_back'],
                $userinfo['account'],
                $userinfo['alipay_usd'],
                $userinfo['alipay_name'],
                $userinfo['alipay_account'],
                $userinfo['alipay_qrcode'],
                $userinfo['weixin_usd'],
                $userinfo['weixin_name'],
                $userinfo['weixin_account'],
                $userinfo['weixin_qrcode'],
                $userinfo['bank_usd'],
                $userinfo['bank_name'],
                $userinfo['bank_province'],
                $userinfo['bank_city'],
                $userinfo['bank_subbranch'],
                $userinfo['bank_card_number'],
                $userinfo['bank_user_name'],
                $userinfo['bank_idcard_munber']
            );
            if (empty($userinfo['nick_name'])) $userinfo['nick_name'] = mobileSubstr($userinfo['mobile']);
            $userList[]=$userinfo;
        }

        $data['onlineUser'] = $userList;
        $data['onlineUserNum'] = $num;
        $data['pageCount'] = ceil($num / $size );

        return $this->success($data);

    }

    public function getLike(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');
        $key = 'live_like_roomid_' . $roomid;
        $count = Cache::get($key);
        if ($count === false) $count = 0;
        $data['likeNum'] = $count;
        return $this->success($data);
    }
    public function setLike(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');
        $key = 'live_like_roomid_' . $roomid;
        Cache::inc($key);
        $count = Cache::get($key);
        $data['likeNum'] = $count;
        return $this->success($data);
    }

    public function getGoodsList(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');

        $roomInfo = (new LiveRoomModel())->getLiveRoomByRoomid($roomid);
        if (empty($roomInfo)){
            return $this->error('没有找到相关直播间数据.');
        }
        $goods_list = [];
        if (empty($roomInfo['goods_ids']) == false){
            $where[] = ['goods_id','in',$roomInfo['goods_ids']];
            $goods_list = (new LiveGoodsModel())->where($where)->select()->toArray();
        }

        $channelGoods = new ChannelGoodsModel();
        $goodsModel = new GoodsModel();
        foreach ($goods_list as &$goods){
            $goods['is_cart'] = 1;
            $proxy_goods = $channelGoods->info($goods['goods_id']);
            if (empty($proxy_goods) == false) {
                $goods['is_cart'] = 0;
            }

            $shopGoods = $goodsModel->info($goods['goods_id']);
            $goods['is_spec'] = $shopGoods['is_spec'];

            $goods['show_stock_num'] = settings('shop_goods_show_stock_num');
            $goods['show_market_price'] = settings('shop_goods_show_market_price');
        }
        $data['goodsList'] = $goods_list;
        return $this->success($data);
    }

    public function getRuleList(){

        $list = (new ChargeRulesModel())->getAllRules();
        $data['ruleList'] = $list;

        return $this->success($data);
    }

    public function getLiveInfo(){
        $roomid = input('roomid', 0, 'intval');
        if (empty($roomid)) return $this->error('参数错误');

        $roomInfo = (new LiveRoomModel())->getLiveRoomByRoomid($roomid);
        if (empty($roomInfo)) return $this->error('直播间不存在.');
        if ($roomInfo['live_status'] != 103) return $this->error('此直播间不存在.');

        $roomInfo['min'] = ceil(($roomInfo['end_time'] - $roomInfo['start_time']) / 60);
        $roomInfo['start_time'] = date('H:i', $roomInfo['start_time']);
        $roomInfo['end_time'] = date('H:i', $roomInfo['end_time']);

        $data['liveInfo'] = $roomInfo;

        return $this->success($data);
    }

    public function getList(){
        $page = input('page',0,'intval');
        $limit = 10;
        $list = (new LiveRoomModel())->getReplayList($page, $limit);

        $data['list'] = $list;
        $data['page_count'] = ceil(count($list) / $limit );

        // 当前时段是否有直播
        $data['isLive'] = false;
        $room = (new LiveRoomModel())->getLastOne();
        if (!empty($room)){
            $data['isLive'] = true;
        }

        return $this->success($data);
    }

}
